package common

import (
	"database/sql"
	_"github.com/go-sql-driver/mysql"
	"strconv"
)

// 连接mysql
func NewMysqlConn() (db *sql.DB,err error) {
	db,err = sql.Open("mysql","root:aA111222333@tcp(liuhengbo.top:3306)/miaosha?charset=utf8")
	return
}

// 获取一行数据
func GetResultRow(rows *sql.Rows) (record map[string]string) {
	columns,_ := rows.Columns()
	scanArgs := make([]interface{},len(columns))
	values := make([]interface{},len(columns))
	record = make(map[string]string)
	// scanArgs中设置values的指针
	for i, _ := range values {
		scanArgs[i] = &values[i]
	}
	for rows.Next() {
		// 此处赋值后,values中也会有值,因为scanArgs中存储的是values的指针
		err := rows.Scan(scanArgs...)
		if err != nil {
			return
		}
	}

	for i, value := range values {
		// 取出db中的field赋值给map的key
		tmp := ""
		switch value.(type) {
		case string:
			tmp =value.(string)
		case []uint8:
			tmp = string(value.([]byte))
		case int:
			tmp = strconv.Itoa(value.(int))
		case int64:
			tmp = strconv.Itoa(int(value.(int64)))
		}

		record[columns[i]] = tmp
	}
	return
}


//获取所有
func GetResultRows(rows *sql.Rows) map[int]map[string]string {
	//返回所有列
	columns, _ := rows.Columns()
	//这里表示一行所有列的值，用[]byte表示
	vals := make([][]byte, len(columns))
	//这里表示一行填充数据
	scans := make([]interface{}, len(columns))
	//这里scans引用vals，把数据填充到[]byte里
	for k, _ := range vals {
		scans[k] = &vals[k]
	}
	i := 0
	result := make(map[int]map[string]string)
	for rows.Next() {
		//填充数据
		rows.Scan(scans...)
		//每行数据
		row := make(map[string]string)
		//把vals中的数据复制到row中
		for k, v := range vals {
			key := columns[k]
			//这里把[]byte数据转成string
			row[key] = string(v)
		}
		//放入结果集
		result[i] = row
		i++
	}
	return result
}

